package com.byls.controller;

import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.MultipartConfigElement;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@CrossOrigin
@Controller
public class Test {

    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setLocation("/static/");
        return factory.createMultipartConfig();
    }
    @CrossOrigin
    @PostMapping( "/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + suffixName;
        // 图片存储地址，例如"E:/imagesServer/"
        String parent = "/home/bylstest/logistics/uploads/image/";
        String imgName = "";
        try {
            File targetFile = new File(parent, fileName);
            // 创建文件夹
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            // 将上传文件存储到服务器中
            file.transferTo(targetFile);
            // 背景图片地址
            imgName = targetFile.getName();

            // 图片显示地址，例如"http://localhost:8080/imgFiles/" + imgName
            imgName = "http://47.95.123.45:8181/uploads/image/" + imgName;
            System.out.println(imgName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imgName;
    }

}
